package com.mxpio.erp.plm.service.impl;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.enums.PlmEnums;
import com.mxpio.erp.common.plm.entity.ProjectInfo;
import com.mxpio.erp.common.plm.entity.ProjectProblem;
import com.mxpio.erp.common.plm.entity.ProjectTask;
import com.mxpio.erp.common.plm.entity.ProjectTaskExecutionLog;
import com.mxpio.erp.common.plm.service.ProjectInfoService;
import com.mxpio.erp.common.plm.service.ProjectProblemService;
import com.mxpio.erp.common.plm.service.ProjectProblemStatusHistoryService;
import com.mxpio.erp.common.plm.service.ProjectTaskService;
import com.mxpioframework.common.exception.MBootException;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.security.service.impl.BaseServiceImpl;
import com.mxpioframework.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 项目问题库
 * @author qb
 * @date 2024-2-20
 */
@Service
@Slf4j
public class ProjectProblemServiceImpl extends BaseServiceImpl<ProjectProblem> implements ProjectProblemService {

    @Autowired
    private ProjectTaskService projectTaskService;

    @Autowired
    private ProjectInfoService projectInfoService;
    @Autowired
    private ProjectProblemStatusHistoryService projectProblemStatusHistoryService;

    @Override
    @Transactional
    public ProjectProblem saveProblem(ProjectProblem projectProblem) {
        ProjectTask projectTask = JpaUtil.getOne(ProjectTask.class, projectProblem.getTaskCode());
        if(projectTask == null){
            throw new MBootException("任务不存在！");
        }
        projectProblem.setStatus(PlmEnums.ProblemStatus.NEW.getCode());
        this.save(projectProblem);
        //记录执行log
        ProjectTaskExecutionLog executionLog = new ProjectTaskExecutionLog();
        executionLog.setTaskCode(projectTask.getTaskCode());
        executionLog.setLogType(PlmEnums.LogType.PROBLEM.getCode());
        executionLog.setApplicant(projectProblem.getCreateBy());
        executionLog.setApplyTime(projectProblem.getCreateTime());
        executionLog.setOriProgress(projectTask.getProgress());
        executionLog.setApplyDesc(projectTask.getReason());
        executionLog.setAuditStatus(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode());
        executionLog.setProblemId(projectProblem.getQuestionCode());
        JpaUtil.save(executionLog);
        return projectProblem;
    }

    @Override
    @Transactional
    public ProjectProblem dealProblem(ProjectProblem projectProblem) {
        List<ProjectTaskExecutionLog> list = JpaUtil.linq(ProjectTaskExecutionLog.class)
                .equal("problemId", projectProblem.getQuestionCode())
                .equal("auditStatus", OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())
                .list();
        ProjectTaskExecutionLog taskExecutionLog = list.get(0);
        if(taskExecutionLog == null ){
            throw new MBootException("任务问题不存在或已处理！");
        }
        String statusBefore = projectProblem.getStatus();

        projectProblem.setRealSolveTime(new Date());
        projectProblem.setStatus(PlmEnums.ProblemStatus.PROCESSED.getCode());
        this.update(projectProblem);

        //保存操作记录
        String remark = "问题处理";
        projectProblemStatusHistoryService.saveHistory(projectProblem,statusBefore,remark);

        taskExecutionLog.setAuditStatus(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode());
        JpaUtil.update(taskExecutionLog);

        return projectProblem;
    }

    @Override
    @Transactional
    public void problemAudit(ProjectProblem projectProblem) {
        List<ProjectTaskExecutionLog> list = JpaUtil.linq(ProjectTaskExecutionLog.class)
                .equal("problemId", projectProblem.getQuestionCode())
                .equal("auditStatus", OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())
                .list();
        if (list.size() == 0) {
            throw new MBootException("任务问题不存在或未处理！");
        }
        ProjectTaskExecutionLog taskExecutionLog = list.get(0);
        if(taskExecutionLog == null ){
            throw new MBootException("任务问题不存在或未处理！");
        }
        String statusBefore = projectProblem.getStatus();

        projectProblem.setStatus(PlmEnums.ProblemStatus.AUDITED.getCode());
        this.update(projectProblem);

        //保存操作记录
        String remark = "问题同意审核";
        projectProblemStatusHistoryService.saveHistory(projectProblem,statusBefore,remark);

        //更新任务log
        taskExecutionLog.setAuditOpinionDesc(projectProblem.getRealLiberation());
        taskExecutionLog.setAuditStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
        taskExecutionLog.setAuditPerson(projectProblem.getUpdateBy());
        taskExecutionLog.setAuditTime(projectProblem.getUpdateTime());
        JpaUtil.update(taskExecutionLog);

    }

    /**
     * 我负责的问题
     * @param page
     * @param criteria
     * @return
     */
    @Override
    @Transactional
    public Page<ProjectProblem> listPageHead(Pageable page, Criteria criteria) {
        criteria = criteria.addCriterion("questionLeader", Operator.LIKE, "%" + SecurityUtils.getLoginUsername() + "%");
        Page<ProjectProblem> projectProblem = this.listPage(ProjectProblem.class, page, criteria);
        return projectProblem;
    }

    /**
     * 我审核的问题
     * @param page
     * @param criteria
     * @return
     */
    @Override
    @Transactional
    public Page<ProjectProblem> listPageAudit(Pageable page, Criteria criteria) {
        //取出所有任务问题
        List<ProjectProblem> list = this.list(ProjectProblem.class, criteria);
        List<ProjectProblem> problem = new ArrayList<>();
        for (ProjectProblem projectProblem : list) {
            ProjectTask byId = projectTaskService.getById(ProjectTask.class, projectProblem.getTaskCode());
            //当有父级任务时
            if (byId != null && byId.getParentTaskCode() != null) {
                //判断当前登陆人是不是根任务大的负责人
                ProjectTask parentTask = projectTaskService.getById(ProjectTask.class, byId.getParentTaskCode());
                if (parentTask != null) {
                    String head = parentTask.getHead();
//                    String[] split = head.split(",");
//                    for (String s : split){
//                        //当登陆人是根任务的负责人时
//                        if (s.equals(SecurityUtils.getLoginUsername())){
//                            problem.add(projectProblem);
//                        }
                    //当登陆人是根任务的负责人时
                    if (head!=null && head.contains(SecurityUtils.getLoginUsername())) {
                        problem.add(projectProblem);
                    }
                    //当登陆人不是根任务的负责人时
                    else {
                        ProjectInfo projectInfo = projectInfoService.getById(ProjectInfo.class, projectProblem.getProCode());
                        String proLeader = projectInfo.getProLeader();
                        String proSecretary = projectInfo.getProSecretary();
                        //判断当前登陆人是不是项目负责人和项目秘书
                        //如果是则把问题添加到集合中
                        //如果不是则不添加到集合中
                        if (proLeader!=null && proLeader.contains(SecurityUtils.getLoginUsername())){
                            problem.add(projectProblem);
                        }else if (proSecretary!=null && proSecretary.contains(SecurityUtils.getLoginUsername())){
                            problem.add(projectProblem);
                        }

//                        if (SecurityUtils.getLoginUsername().contains(proLeader) || SecurityUtils.getLoginUsername().contains(proSecretary)) {
//                            String[] split1 = proLeader.split(",");
//                            String[] split2 = proSecretary.split(",");
//                            for (String proLeader1 : split1){
//                                for (String proSecretary1 : split2){
                            //判断当前登陆人是不是项目负责人和项目秘书
                            //如果是则把问题添加到集合中
                            //如果不是则不添加到集合中
//                                    if (proLeader1.equals(SecurityUtils.getLoginUsername()) || proSecretary1.equals(SecurityUtils.getLoginUsername())){
//                            problem.add(projectProblem);
//                                    }
//                                }
//                            }
//                        }
                    }
                }
            } else {
                ////当没有父级任务时
                String head = byId.getHead();
                if (head.contains(SecurityUtils.getLoginUsername())) {
                    problem.add(projectProblem);
                }
//            String[] split = head.split(",");
//            for (String s : split){
//                if (s.equals(SecurityUtils.getLoginUsername())){
//                    problem.add(projectProblem);
//                }
//            }
            }
        }
        PageImpl<ProjectProblem> projectProblems = new PageImpl<>(problem, page, problem.size());
        return projectProblems;
    }

    @Override
    @Transactional
    public void problemAuditNo(ProjectProblem projectProblem) {
        List<ProjectTaskExecutionLog> list = JpaUtil.linq(ProjectTaskExecutionLog.class)
                .equal("problemId", projectProblem.getQuestionCode())
                .equal("auditStatus", OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())
                .list();
        if (list.size() == 0) {
            throw new MBootException("任务问题不存在或未处理！");
        }
        ProjectTaskExecutionLog taskExecutionLog = list.get(0);
        if(taskExecutionLog == null ){
            throw new MBootException("任务问题不存在或已处理！");
        }
        String statusBefore = projectProblem.getStatus();

        projectProblem.setStatus(PlmEnums.ProblemStatus.NEW.getCode());
        this.update(projectProblem);

        //保存操作记录
        String refuseReason = projectProblem.getRefuseReason();//拒绝原因
        projectProblemStatusHistoryService.saveHistory(projectProblem,statusBefore,refuseReason);

        //更新任务log
        taskExecutionLog.setAuditOpinionDesc(projectProblem.getRealLiberation());
        taskExecutionLog.setAuditStatus(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode());
        taskExecutionLog.setAuditPerson(projectProblem.getUpdateBy());
        taskExecutionLog.setAuditTime(projectProblem.getUpdateTime());
        JpaUtil.update(taskExecutionLog);
    }

}
